import datetime
import glob
import json
import os.path
import re
import shutil
import threading
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.dates import AutoDateLocator, DateFormatter

from StressAna.Lib.DataAna.AnkeDataAna import AnkeAna
from StressAna.Lib.DataAna.TDDataAna import TDAna
from StressAna.Lib.DataAna.MonDataAna import MonAna
from StressAna.Lib.Utils import DateTimeUtil

srcFile = r'D:\LK\TMV煤矿项目\应力数据\obsdata\2\Y07'
dstFile = r'D:\LK\Project\test\StressData'
chn = 2

start_month = 3
end_month = 3
start_day = 1
end_day = 9

start_check_day = 1
end_check_day = 9
start_check_hour = 00
end_check_hour = 23


# srcFile = r'D:\LK\TMV煤矿项目\应力数据\obsdata\1\Y07'
# dstFile = r'D:\LK\Project\test\StressData'
# chn = 2
# start_day = 28
# end_day = 30

def main():
    mod_flag = False
    for i in range(start_day, end_day):
        file_name = f'2024-{start_month:0>2d}-{i:0>2d}.txt'
        sid = srcFile[-3:]
        src_file = f"{srcFile}/{sid}_{file_name}"
        dst_file = f"{dstFile}/{sid}/{sid}_{file_name}"
        if not Path(dst_file).parent.exists():
            os.makedirs(Path(dst_file).parent)
        print(src_file)

        with open(src_file, 'r') as f:
            lines = f.read().splitlines()

        with open(dst_file, 'w') as f:
            f.write(f"{lines[0]}\n")
            for line in lines[1:]:
                if f'2024-{start_month:0>2d}-{start_check_day:0>2d} {start_check_hour:0>2d}:00:00' in line:
                    mod_flag = True
                    continue
                if f'2024-{end_month:0>2d}-{end_check_day:0>2d} {end_check_hour:0>2d}:00:00' in line:
                    mod_flag = False
                if mod_flag:
                    a = line.split(',')
                    if chn == 1:
                        content = f"{a[0]},-9999,{a[2]}\n"
                    if chn == 2:
                        content = f"{a[0]},{a[1]},-9999\n"
                    f.write(content)
                else:
                    f.write(f"{line}\n")


def draw(data_list=None, data_list2=None, labels=None):
    if data_list is None:
        data_list = []
    if data_list2 is None:
        data_list2 = []
    if labels is None:
        labels = []
    # 创建一个Figure
    width = 12
    height = 8
    dpi = 100
    fig = plt.figure(figsize=(width, height), dpi=dpi, tight_layout=True)  # tight_layout: 用于去除画图时两边的空白
    plt.rcParams['figure.figsize'] = (width, height)
    plt.rcParams["font.sans-serif"] = ["Microsoft YaHei"]  # 设置默认字体
    plt.rcParams["axes.unicode_minus"] = False  # 坐标轴正确显示正负号
    ax = fig.add_subplot(111)

    data_legend = []
    for idata in data_list:
        line = ax.plot(idata[0], idata[1])
        data_legend.append(line[0])

    if data_list2:
        ax2 = ax.twinx()
        for idata in data_list2:
            line = ax2.plot(idata[0], idata[1], c='purple', alpha=0.8, linestyle='--')
            data_legend.append(line[0])
        ax2.set_ylabel("摄氏度/℃")
    plt.legend(data_legend, labels, loc=9, bbox_to_anchor=(0.5, -0.2), shadow=True, fancybox=True, ncol=4)

    ax.set_title("对比分析", pad=25)
    ax.set_xlabel("时间")
    ax.set_ylabel("Mpa")

    locator = AutoDateLocator()
    date_fmt = DateFormatter("%Y-%m-%d %H:%M:%S")
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(date_fmt)
    ax.tick_params(direction='in', length=6, width=2, labelsize=8)
    ax.xaxis.set_tick_params(labelrotation=45)
    plt.tight_layout()
    plt.show()
    # fig.savefig('对比分析.png')


class Anke_Data(object):
    def __init__(self, file):
        self.srcFile = file
        self._raw_df = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
        self._init()

    def _init(self):
        _df = pd.DataFrame(columns=['传感器编号', '时间', '通道1-监测值', '通道2-监测值'])
        try:
            _raw_dict = pd.read_excel(self.srcFile, sheet_name=None,
                                      usecols=['传感器编号', '时间', '通道1-监测值', '通道2-监测值'],
                                      dtype={'时间': 'datetime64[ns]', '传感器编号': 'str'})
        except ValueError:
            print(f'{self.srcFile}解析数据失败')
            return
        for key, item in _raw_dict.items():
            _df = _df._append(item)
        _df.rename(columns={'传感器编号': 'sID', '时间': 'time', '通道1-监测值': 'ch1', '通道2-监测值': 'ch2'},
                   inplace=True)
        self._raw_df = self._raw_df._append(_df)


def main1():
    dirs = glob.glob(r'D:\LK\TMV煤矿项目\应力数据\AK\思科赛德数据/**/*.xlsx', recursive=True)
    # threadPool = ThreadPoolExecutor(max_workers=10, thread_name_prefix="get_all_local_event_dict_json_")
    # for file in dirs:
    #     future = threadPool.submit(base_test, file)
    # threadPool.shutdown(wait=True)

    with ThreadPoolExecutor(max_workers=10) as threadPool:
        for file in dirs:
            threadPool.submit(base_test, file)

    DF_ALL = pd.DataFrame(columns=['sID', 'time', 'ch1', 'ch2'])
    for df in DATA_LIST:
        DF_ALL._append(df)
    DF_ALL.to_csv('ak_data.csv.gz', compression='gzip', index=False)
    print()

def base_test():
    df1 = TDAna(r"D:\LK\TMV煤矿项目\应力数据\obsdata\1\G12\G12_2024-01-24.txt").df
    df2 = TDAna(r"D:\LK\TMV煤矿项目\应力数据\obsdata\1\G12\G12_2024-01-24.txt").df
    df = pd.concat([df1, df2])
    # df = df1.merge(df2, on=['sID', 'time'], how='left')
    # df = pd.concat([df1,df2], join='inner', axis=1)
    x = []
    y = []
    for time, dfi in df.groupby('time'):
        x.append(time)
        y.append(dfi.iloc[0]['ch1'])
    print()


def out_td_data():
    src_path = r'D:\LK\TMV煤矿项目\应力数据\obsdata\1'
    dst_path = r'D:\LK\TMV煤矿项目\应力数据\obsdata-20240117-20240323\1'
    for dir in glob.glob(f"{src_path}/**/*.txt", recursive=True):
        date = Path(dir).stem.split('_')[1]
        if '2024-01-17' <= date <= '2024-03-23':
            dst_data_path = dir.replace(src_path, dst_path)
            if not Path(dst_data_path).parent.exists():
                os.makedirs(Path(dst_data_path).parent)
            shutil.copy(dir, dst_data_path)


def mod_flash_data():
    flash_data_path = r'D:\LK\Project\test\flashdata'
    date_list = DateTimeUtil.get_date_str_list_by_date_range('2024-01-22', '2024-01-30', '%Y-%m-%d')
    for i, date in enumerate(date_list[:-1]):
        for data_path in glob.glob(f"{flash_data_path}/*.json"):
            sid = Path(data_path).stem[0]
            with open(data_path, 'r') as f:
                json_data = json.loads(f.read())
            json_data[0]['Tm'] = f"{date} 00:00:00"
            json_data[1]['Tm'] = f"{date} 12:00:00"
            json_data[2]['Tm'] = f"{date_list[i + 1]} 00:00:00"
            save_data_path = f"{flash_data_path}/{date}/{Path(data_path).name}"
            if not os.path.exists(Path(save_data_path).parent):
                os.makedirs(Path(save_data_path).parent)
            with open(save_data_path, 'w') as f:
                f.write(json.dumps(json_data))


def mod_obsdata():
    id = 1
    path1 = rf'D:\LK\TMV煤矿项目\应力数据\TD\G\G01\G01_2024-03-11.txt'
    path2 = rf'D:\LK\TMV煤矿项目\应力数据\TD\G\G01\G01_2024-03-10.txt'
    df1 = TDAna(path1).df
    df2 = TDAna(path1).df
    df3 = TDAna(path2).df
    df = pd.concat([df1, df2, df3])
    df.loc[:, 'time'] = df.loc[:, 'time'].astype('datetime64[ns]')
    df['ch2'] = df['ch2'].astype('float')
    print()


def bushu():
    a = {'G01': 'G01', 'G02': 'G02', 'G03': 'G03', 'G04': 'G05', 'G05': 'G06', 'G06': 'G08'}

    src_date = '2024-01-20'
    dst_date = '2024-01-29'
    src_path = rf'D:\LK\TMV煤矿项目\应力数据\obsdata\1'
    dst_path = rf'D:\LK\Project\test\StressData'
    for key, value in a.items():
        i_src_path = f"{src_path}/{value}/{value}_{src_date}.txt"
        i_dst_path = f"{dst_path}/{key}/{key}_{dst_date}.txt"
        shutil.copy(i_src_path, i_dst_path)
        with open(i_dst_path, 'r') as f:
            lines = f.read().splitlines()
        with open(i_dst_path, 'w') as f:
            _sID, _date, sampRate = lines[0].split(',')
            lines[0] = f"{key[-1]},{_date},{sampRate}"
            for line in lines:
                line = line.replace(src_date, dst_date)
                f.write(f"{line}\n")


def test():
    c = '2024-05-31'
    b = (datetime.datetime.strptime(c, '%Y-%m-%d') + datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    a = []
    intel = 30 / 100
    rest_dis = 50 - 30
    # for i in range(1, 27):
    for i in range(100, 0, -1):
        a.append(-(i * intel + rest_dis))
    print(a)

if __name__ == '__main__':
    test()
